<?php
/**
 * Created by PhpStorm.
 * User: wuchao
 * Date: 2020/5/19
 * Time: 15:38
 */

namespace app\api\model;

use \Exception;
use think\facade\Db;
use \think\response\Json;

class OrderModel
{
    private static $_table = 'order'; // 用户表
    private static $_order_status = 'order_status';//订单记录生成
    private static $_goods_specific = 'goods_specific';//商品规格表

    /**生成订单
     * @param array $input
     * @return Json
     */
    public static function NewOrder($input)
    {
        try {
            Db::startTrans();
            $goodsData = json_decode($input['goodsData'], true);//转换商品数据
            if (empty($goodsData)) return jsonFail('商品数据错误');
            $goods_attr_id = array_column($goodsData, 'goods_attr_id');//商品规格ID
            $attr_data = Db::table(self::$_goods_specific)->where('id', 'in', $goods_attr_id)->field('price,goods_id,center_stock')->select()->toArray();
            $out_attrData = [];
            //组合商品属性数据
            foreach ($attr_data as $v){
                if (!key_exists($v['goods_id'], $out_attrData)) {
                    $out_attrData[$v['goods_id']] = $v;
                }
            }
            $out_goodsData = [];
            //组合商品属性数据
            foreach ($goodsData as $v){
                if (!key_exists($v['goods_id'], $out_goodsData)) {
                    $out_goodsData[$v['goods_id']] = $v;
                }
            }
            foreach ($out_goodsData as $key => $value) {
                if ($value['num']<$out_attrData[$key]['center_stock']) {//判断库存

                } else {
                    return jsonFail('商品库存不够', $value['goods_id']);
                }
            }
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail('系统错误~',$e->getMessage());
        }
    }
}